package com.gaoxk.distributeReq;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;


/**
 * 返回值输出代理类
 *
 * @Title: ResponseWrapper
 * @Description:
 * @author kokJuis
 * @date 上午9:52:11
 */
//public class ResponseWrapper extends HttpServletResponseWrapper
public class ResponseWrapper extends HttpServletResponseWrapper {

    private ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    private PrintWriter printWriter = new PrintWriter(outputStream);
    //new OutputStreamWriter(byteArrayOutputStream, StandardCharsets.UTF_8), true

    private static final Logger LOG = LoggerFactory.getLogger(ResponseWrapper.class);


    public ResponseWrapper(HttpServletResponse response) {
        super(response);
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        return printWriter;
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return new ServletOutputStream() {
            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setWriteListener(WriteListener listener) {

            }

            @Override
            public void write(int b) throws IOException {
                outputStream.write(b);
            }
        };
    }

    public void flush(){
        try {
            printWriter.flush();
            printWriter.close();
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public ByteArrayOutputStream getByteArrayOutputStream(){
        return outputStream;
    }


    public String getTextContent() throws UnsupportedEncodingException {
        flush();
        // 1. 获取响应的编码（优先从响应头获取，默认ISO-8859-1）
        String encoding = getResponse().getCharacterEncoding();
        LOG.info("Response encoding: " + encoding);
        // 2. 若编码为空或不支持，默认使用UTF-8（避免null异常）
        if (encoding == null || !isEncodingSupported(encoding)) {
            if(encoding == null){
                LOG.warn("Response encoding is null, use UTF-8 as default.");
            }
            encoding = "UTF-8";
        }
        // 3. 用实际编码转换字节数组为字符串
        return outputStream.toString(encoding);
        //return outputStream.toString(StandardCharsets.UTF_8.name());
        //return outputStream.toString();
    }

    /**
     * 检查JVM是否支持指定编码
     */
    private boolean isEncodingSupported(String encoding) {
        try {
            "".getBytes(encoding);
            return true;
        } catch (UnsupportedEncodingException e) {
            LOG.warn("Encoding " + encoding + " is not supported.");
            return false;
        }
    }
}